package com.happok.onlineclass.usermanagement.setting.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.happok.onlineclass.usermanagement.common.utils.Sm4Util;
import com.happok.onlineclass.usermanagement.setting.dao.EmailDAO;
import com.happok.onlineclass.usermanagement.setting.dto.EmailSettingDTO;
import com.happok.onlineclass.usermanagement.setting.po.EmailPO;
import com.happok.onlineclass.usermanagement.setting.service.EmailDaoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * 接口分类                        yapi 分类文件夹
 * 功能说明
 *
 * @author : chenac
 * @module 项目名称/模块名          yapi 项目组/子项目
 * @date : 2021/10/9 14:29
 */
@Service
public class EmailDaoServiceImpl implements EmailDaoService {

    @Autowired
    private EmailDAO emailDAO;

    @Override
    public EmailPO getEmail() {
        LambdaQueryWrapper<EmailPO> queryWrapper = new LambdaQueryWrapper<>();
        EmailPO emailPO = emailDAO.selectOne(queryWrapper);
        EmailPO resultEmailPO = new EmailPO();
        if (ObjectUtils.isEmpty(emailPO)) {
            return resultEmailPO;
        }
        BeanUtils.copyProperties(emailPO, resultEmailPO);
        if (!ObjectUtils.isEmpty(emailPO.getPassword())) {
            resultEmailPO.setPassword(Sm4Util.decrypt(emailPO.getPassword()));
        }
        if (!ObjectUtils.isEmpty(emailPO.getAuthorizationCode())) {
            resultEmailPO.setAuthorizationCode(Sm4Util.decrypt(emailPO.getAuthorizationCode()));
        }
        return resultEmailPO;
    }

    @Override
    public void updateEmailSetting(EmailSettingDTO emailSetting) {
        if (!ObjectUtils.isEmpty(emailSetting.getPassword())) {
            emailSetting.setPassword(Sm4Util.encrypt(emailSetting.getPassword()));
        }
        if (!ObjectUtils.isEmpty(emailSetting.getAuthorizationCode())) {
            emailSetting.setAuthorizationCode(Sm4Util.encrypt(emailSetting.getAuthorizationCode()));
        }
        LambdaUpdateWrapper<EmailPO> updateWrapper = new LambdaUpdateWrapper<>();
        EmailPO updateEmail = new EmailPO();
        BeanUtil.copyProperties(emailSetting, updateEmail);
        emailDAO.update(updateEmail, updateWrapper);
    }
}